<template>
    <div>
        <el-dialog 
            :title="storeId == 0 ? '新建站点' : '编辑站点'" 
            :visible.sync="localDialogVisible"
            @close="handleClose"
            :show-close="true" 
            width="800px" 
            z-index="99"
            >
            <el-form ref="form" :model="form" label-width="100px">
                <el-form-item label="站点名称">
                    <el-input v-model="form.name" placeholder="请填写站点名称"></el-input>
                </el-form-item>
                <el-form-item label="所属加盟商">
                    <franchiseList v-model="form.franchiseId"></franchiseList>
                </el-form-item>
                <el-form-item label="所属地区">
                    <cityList v-model="form.cityid" :placeholder="cityPlaceholder" @change="SelectCity" :setStyle="{'width':'100%'}"></cityList>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input id='tipinput' v-model="form.address" placeholder="请输入地址(街道、楼牌等)"
                        prefix-icon="el-icon-location-information">
                        <el-button slot="append" icon="el-icon-search" id="geoCode" :loading="loading">搜索</el-button>
                    </el-input>
                    <div id="container" class="e-m-t-10" style="width:100%;height: 300px;"></div>
                    <div id="panel" style="display:none"></div>
                    <div>经纬度：{{ form.lat }}，{{ form.lng }}</div>
                </el-form-item>
                <el-form-item label="营业时间">
                    <el-input v-model="form.servicetime"></el-input>
                </el-form-item>
                <el-form-item label="联系号码">
                    <el-input v-model="form.telephone"></el-input>
                </el-form-item>
                <el-form-item label="是否发放积分">
                    <el-switch v-model="form.isgrantIntegral"></el-switch>
                </el-form-item>
                <!-- 上传封面 -->
                <el-form-item label="上传封面" prop="icon">
                    <cropper-upload :zoomScale='[1, 1]' :isCropper="true" @getUpload="myhandleFilesSuccess"
                        class="avatar-uploader">
                        <img v-if="form.icon" :src="fileURL + form.icon" class="avatar">
                        <div class="avatar-uploader-icon" v-else>
                            <div><i class="el-icon-plus"></i></div>
                            <div class="e-font-14">上传图片</div>
                        </div>
                    </cropper-upload>
                    <div class="tips">建议上传尺寸比例为200*200 </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="$emit('close', false)">取消</el-button>
                <el-button type="primary" @click="$emit('submit', storeId,form)">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import cityList from '@/components/form-select-type/cityList.vue'
    import franchiseList from '@/components/form-select-type/franchiseList.vue'
    export default {
        components: {
            cityList,
            franchiseList
        },
        props:{
            // 站点id
            storeId:{
                type: Number,
                default: 0
            },
            // 是否显示
            dialogVisible:{
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                localDialogVisible: this.dialogVisible, // 创建本地副本
                loading: false,
                form: {
                    cityid: 0,//地区Id
                    address: "",//详细地址
                    lat: 23.625349,//纬度
                    lng: 113.042648,//经度
                    name: "",//名称
                    telephone: "",//电话
                    icon: "",//图标
                    franchiseId: "",//站点类型
                    serviceTime: "",//营业时间
                    isgrantIntegral: true,//站点回收是否发放积分
                },
                cityPlaceholder: ''
            }
        },
        watch:{
            dialogVisible(newVal){
                this.localDialogVisible = newVal
                if(newVal){
                    this.initMap()
                }
                if(this.storeId > 0){
                    this.getDetails()
                }
            },
            localDialogVisible(newVal) { // 向父组件传递变化
                this.$emit('update:dialogVisible', newVal)
            }
        },
        mounted() {
            // this.getListStoreType()
        },
        methods: {
            getDetails(){
                this.$axios.get('/Store/Details?id='+this.storeId).then((res)=>{
                    this.form = {
                        id: res.id,
                        cityId: res.address.cityid,
                        address: res.address.address,//详细地址
                        lat: res.address.lat,
                        lng: res.address.lng,
                        name: res.name,//名称
                        // icon: res.icon,
                        franchiseId: res.franchiseid,
                        isgrantIntegral: res.isgrantintegral,
                        telephone: res.telephone,//电话
                        icon: res.icon,//图标
                        servicetime: res.servicetime,//营业时间
                    }
                    this.cityPlaceholder = res.address.citynames.replace(/,/g, '-')
                })
            },
            handleClose(e){
                // 关闭时的自定义逻辑
                // this.$emit('close', false)
            },
            initMap() {
                let that = this

                this.$AMapLoader.load({
                    key: this.AMapSetting.key,             // 申请好的Web端开发者Key，首次调用 load 时必填
                    version: this.AMapSetting.version,      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
                }).then((AMap) => {
                    var map = new AMap.Map("container", {  //设置地图容器id
                        zoom: 15, //设置地图的缩放级别
                        zooms: [3, 20],
                        resizeEnable: true,
                        expandZoomRange: true,
                        center: [this.form.lng, this.form.lat], //初始化地图中心点位置
                    });

                    if(this.storeId > 0){
                        new AMap.Marker({
                            map:map,
                            position: [this.form.lng, this.form.lat],
                        })
                    }

                    //输入提示
                    // 实例化Autocomplete
                    var autoOptions = {
                        // input 为绑定输入提示功能的input的DOM ID
                        city: '清远',
                        input: 'tipinput'
                    }
                    var Autocomplete = new AMap.Autocomplete(autoOptions);

                    // var placeSearch1 = new AMap.PlaceSearch({
                    //     city: '清远',
                    //     map: map
                    // })
                    // AMap.event.addListener(Autocomplete, 'select', (e) => {

                    //     //TODO 针对选中的poi实现自己的功能
                    //     placeSearch1.search(e.poi.name)

                    //     // e.poi.location
                    //     console.log('lnglat:', e.poi.location)
                    //     let lnglat = e.poi.location
                    //     this.form.lat = lnglat.lat
                    //     this.form.lng = lnglat.lng
                    // })

                    // 搜索按钮绑定事件
                    var button = document.getElementById('geoCode');
                    var marker = [];
                    button.addEventListener("click", () => {
                        var keywords = this.form.address;

                        var autoOptions = {
                            city: '0763'
                        }
                        var placeSearch = new AMap.PlaceSearch(autoOptions);
                        placeSearch.search(keywords, function (status, result) {
                            // 搜索成功时，result即是对应的匹配数据
                            console.log('status:', status)
                            console.log('result:', result)
                            if (status == "error") {
                                if (result == "USER_DAILY_QUERY_OVER_LIMIT") {
                                    that.$message.error('已超出了该高德地图api调用次数限制');
                                }
                                return
                            }

                            var pois = result.poiList.pois;
                            // 移除已创建的 marker
                            map.remove(marker);
                            marker = [];

                            for (var i = 0; i < pois.length; i++) {
                                var poi = pois[i];
                                marker[i] = new AMap.Marker({
                                    position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                                    title: poi.name
                                });
                                marker[i].content = pois[i].address
                                marker[i].location = pois[i].location
                            }
                            //将创建的点标记添加到已有的地图实例：
                            map.add(marker);
                            map.setFitView();

                            var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
                            marker.forEach((item) => {
                                item.on('click', function (e) {
                                    let obj = e.target

                                    infoWindow.setContent(obj.content);
                                    infoWindow.open(map, obj.location);

                                    that.form.lat = obj.location.lat
                                    that.form.lng = obj.location.lng
                                    that.form.address = obj.content
                                });
                            })
                        })
                    })

                }).catch(e => {
                    console.log(e);
                })
            },
            //选择城市
            SelectCity(v) {
                this.form.cityid = v;
            },
            //加载城市
            loadCity(node, resolve) { 
                if (node.level == 0) {
                    this.$axios.post('/city/List', {
                        pageIndex: 1,
                        pageSize: 9999,
                        pId: 0
                    }).then((res) => {
                        node = res.rows?.map(function (c) {
                            return {
                                id: c.id,
                                name: c.name
                            }
                        });
                        resolve(node);
                    })
                } else {
                    if (node.level < 5) {
                        this.$axios.post('/city/List', {
                            pageIndex: 1,
                            pageSize: 9999,
                            pId: node.value
                        }).then((res) => {
                            node = res.rows?.map(function (c) {
                                return {
                                    id: c.id,
                                    name: c.name
                                }
                            });
                            resolve(node);
                        })
                    } else {
                        resolve();
                    }
                }
            },
            //图片
            myhandleFilesSuccess(res, file) {
                console.log(res,file)
                if (file.status === "success") {
                    this.loading = false
                    this.form.icon = res.path
                    this.$forceUpdate()
                }
            }
        }
    }
</script>